package org.ly.uap.client.util;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.HostnameVerifier;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class HttpRemote {

    private static final Log LOG = LogFactory.getLog(HttpRemote.class);
    private static boolean enabledFlag = true;
    public static boolean isEnabledFlag(){
        return enabledFlag;
    }
    /**
     * 以Post方法访问
     * @param url 请求地址
     * @param argsMap 携带的参数
     * @return String 返回结果
     * @throws Exception
     */
    public static String postMethod(String url, Map<String, Object> argsMap) throws Exception {
        byte[] dataByte = null;
        // 创建HttpClientBuilder
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        // HttpClient
        CloseableHttpClient httpClient = httpClientBuilder.build();
        HttpPost httpPost = new HttpPost(url);
        // 设置参数
        UrlEncodedFormEntity encodedFormEntity = new UrlEncodedFormEntity(setHttpParams(argsMap), "UTF-8");
        httpPost.setEntity(encodedFormEntity);
        // 执行请求
        HttpResponse httpResponse = httpClient.execute(httpPost);
        // 获取返回的数据
        HttpEntity httpEntity = httpResponse.getEntity();
        if (httpEntity != null) {
            byte[] responseBytes = EntityUtils.toByteArray(httpEntity);//拿到返回结果字节流
            dataByte = responseBytes;
            httpPost.abort();
        }
        // 将字节数组转换成为字符串

        String result =  new String(dataByte, "UTF-8");
        System.out.println("cas result:"+result);
        return result;
    }
    private static List<NameValuePair> setHttpParams(Map<String, Object> argsMap){
        List<NameValuePair> urlParameters = new ArrayList<>();
        if(argsMap == null || argsMap.isEmpty())
            return urlParameters;
        for(Map.Entry<String,Object> entry : argsMap.entrySet()){
            NameValuePair nameValuePair = new BasicNameValuePair(entry.getKey(), entry.getValue().toString());
            urlParameters.add(nameValuePair);
        }
        return urlParameters;
    }
    public static String getResponseFromServer(final URL constructedUrl, final HostnameVerifier hostnameVerifier, final String encoding) {
        System.out.println("==========getResponseFromServer begin=======================");
        System.out.println("constructedUrl:"+constructedUrl.toString());
        System.out.println("hostnameVerifier:"+hostnameVerifier.toString());
        System.out.println("encoding:"+encoding);
        URLConnection conn = null;
        try {
//            conn = constructedUrl.openConnection();
//            if (conn instanceof HttpsURLConnection) {
//                ((HttpsURLConnection)conn).setHostnameVerifier(hostnameVerifier);
//            }
//            final BufferedReader in;
//
//            if (CommonUtils.isEmpty(encoding)) {
//                in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
//            } else {
//                in = new BufferedReader(new InputStreamReader(conn.getInputStream(), encoding));
//            }
//
//            String line;
            final StringBuilder stringBuffer = new StringBuilder(255);
//
//            while ((line = in.readLine()) != null) {
//                stringBuffer.append(line);
//                stringBuffer.append("\n");
//            }
            stringBuffer.append(HttpRemote.postMethod(constructedUrl.toString(),null));
            return stringBuffer.toString();
        } catch (final Exception e) {
            LOG.error(e.getMessage(), e);
            throw new RuntimeException(e);
        } finally {
            if (conn != null && conn instanceof HttpURLConnection) {
                ((HttpURLConnection)conn).disconnect();
            }
        }
    }
}
